package keeto.com.vn.bms.ui.fragment;

import java.util.ArrayList;

import keeto.com.vn.bms.config.BMSCore;
import keeto.com.vn.bms.model.InfoMessegerModel;
import keeto.com.vn.bms.network.IBMSProtocol;
import keeto.com.vn.bms.ui.activity.R;
import keeto.com.vn.bms.ui.adapter.InfoChatAdapter;
import keeto.com.vn.bms.ui.fragment.ChatManagerFragment.ChatManagerListener;
import keeto.com.vn.bms.ui.widget.HomeChatHintsListener;
import keeto.com.vn.bms.utils.BMSListener;
import keeto.com.vn.bms.utils.BMSSharedPreferences;
import keeto.com.vn.bms.utils.Utils;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ChatAdminFragment extends Fragment implements OnClickListener, OnRefreshListener<ListView>{

	private PullToRefreshListView mListView;
	private ProgressBar mBar;
	private ArrayList<InfoMessegerModel> mArrayList = new  ArrayList<InfoMessegerModel>();
	private int PageNumber = 1;
	private int typeofMsg=1;
	private final int PAGE_LIMIT = 10;
	private ChatManagerListener listener = new ChatManagerListener();
	private BMSSharedPreferences preferences;
	private InfoMessegerModel messegerModel;
	private Button btnSend;
	private EditText edtMsgChat;
	private InfoChatAdapter mAdapter;
	private static String CurrenmsgId;
	private String GroupID = "4";
	private HomeChatHintsListener mListener;
	private String IDMsg = null;
	private Handler mHandler = new Handler();


	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.chat_manager_fragment_layout,null);
		preferences = new BMSSharedPreferences(getActivity());
		messegerModel = new InfoMessegerModel();
		initView(v);
		mListener = new HomeChatHintsListener() {

			@Override
			public void sendMsgHint(String hints) {
				// TODO Auto-generated method stub
				if (edtMsgChat != null){
					edtMsgChat.setText(hints);
				}
			}

			@Override
			public void deletemsgAdmin() {
				// TODO Auto-generated method stub
				if (mAdapter.getCount() >0){
					IDMsg = ((InfoMessegerModel) mAdapter.getItem(mAdapter.getCount()-1)).getMsgID();
					if (IDMsg != null && !IDMsg.equals("")){
						mBar.setVisibility(View.VISIBLE);
						BMSCore.getInstance(getActivity()).taskDeleteMsg(IDMsg, preferences.getUserAuthKey(getActivity()), listener);
					}
				}
			}

			@Override
			public void deletemsgManager() {
				// TODO Auto-generated method stub
				
			}


		};
		return v;
	}

	private void initView(View v){
		mListView = (PullToRefreshListView)v.findViewById(R.id.list_chat);
		mBar = (ProgressBar)v.findViewById(R.id.progressbar_chat);
		mBar.setVisibility(View.GONE);
		btnSend = (Button)v.findViewById(R.id.btn_Send_msg);
		btnSend.setOnClickListener(this);
		edtMsgChat = (EditText)v.findViewById(R.id.edtChatmsg);
		mArrayList.clear();
		mAdapter = new InfoChatAdapter(getActivity(), mArrayList);
		mListView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();

		mListView.setOnRefreshListener(this);
		mListView.setMode(Mode.BOTH);
		CurrenmsgId = messegerModel.getMsgID();
		PageNumber = 1;
		BMSCore.getInstance(this.getActivity()).taskGetMessegertwoGroup(GroupID, preferences.getUserAuthKey(this.getActivity()), PAGE_LIMIT,PageNumber,listener);

	}
	public HomeChatHintsListener getListener(){
		return mListener;
	}
	private void SendComment(){
		String contentmsg = "";
		contentmsg =edtMsgChat.getText().toString();
		if(!Utils.validateValue(contentmsg).equals("")){
			mBar.setVisibility(View.VISIBLE);

			BMSCore.getInstance(this.getActivity()).taskSendMsgtoGroups("Send to Manager" , contentmsg, GroupID, preferences.getUserAuthKey(this.getActivity()), listener);

		}
	}
	class ChatManagerListener extends BMSListener{

		@Override
		public void finishGetMessegerTwoGroups(final int returnCode, final int pageCount,
				final ArrayList<InfoMessegerModel> ListDetailMsg) {
			// TODO Auto-generated method stub
			super.finishGetMessegerTwoGroups(returnCode, pageCount, ListDetailMsg);
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (returnCode == IBMSProtocol.STATUS_CODE_OK && ListDetailMsg != null){						
						if (PageNumber ==1){
							mArrayList.clear();
						}
						if (PageNumber < pageCount){
							PageNumber +=1;
						}else{
							PageNumber =-1;
						}
						for (int i = ListDetailMsg.size()-1 ; i >= 0; i--){
							mArrayList.add(ListDetailMsg.get(i));
							if (ListDetailMsg.get(i).isRead()== false){
								final String msgId = ListDetailMsg.get(i).getMsgID();
								mHandler.post(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										BMSCore.getInstance(getActivity()).taskSetReadMessage(msgId, preferences.getUserAuthKey(getActivity()), listener);

									}
								});
							}
						}
						mAdapter.notifyDataSetChanged();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_GENERIC_FAIL){
						Toast.makeText(getActivity(),getActivity().getResources().getString(R.string.error_perpose), Toast.LENGTH_SHORT).show();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_GENERIC_FAIL_CONECTTION){
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_network_connection), Toast.LENGTH_SHORT).show();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_EXIT_RECORD){
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_data_server), Toast.LENGTH_SHORT).show();
					} 
					mBar.setVisibility(View.GONE);
					mListView.onRefreshComplete();
				}
			});
		}


		@Override
		public void finishSendMsgtoGroups(final int returnCode, String resultMsg,
				String MsgId) {
			// TODO Auto-generated method stub
			super.finishSendMsgtoGroups(returnCode, resultMsg, MsgId);
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						PageNumber=1;
						edtMsgChat.setText("");
						mListView.setRefreshing();
					}else{
						edtMsgChat.setText("");
					}
					mBar.setVisibility(View.GONE);
				}
			});
		}
		@Override
		public void finishDeleteMsg(final int returnCode, String resultMsg) {
			// TODO Auto-generated method stub
			super.finishDeleteMsg(returnCode, resultMsg);
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					mBar.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						PageNumber = 1;
						mArrayList.clear();
						mAdapter.notifyDataSetChanged();
						mBar.setVisibility(View.VISIBLE);
						BMSCore.getInstance(getActivity()).taskGetMessegertwoGroup(GroupID, preferences.getUserAuthKey(getActivity()), PAGE_LIMIT,PageNumber,listener);
					}
				}
			});
		}

	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_Send_msg:
			SendComment();
			break;
		default:
			break;
		}
	}
	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		mBar.setVisibility(View.VISIBLE);
		if (PageNumber >0){
			if (refreshView.getCurrentMode() == Mode.PULL_FROM_START){
				BMSCore.getInstance(this.getActivity()).taskGetMessegertwoGroup(GroupID, preferences.getUserAuthKey(this.getActivity()), PAGE_LIMIT,PageNumber,listener);
			}else{
				PageNumber = 1;
				BMSCore.getInstance(this.getActivity()).taskGetMessegertwoGroup(GroupID, preferences.getUserAuthKey(this.getActivity()), PAGE_LIMIT,PageNumber,listener);
			}
		}else{
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					mBar.setVisibility(View.GONE);
					mListView.onRefreshComplete();	
				}
			});
		}
	}
}
